class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> v;
        stack<TreeNode*> st;


        TreeNode* cur = root;
        TreeNode* prev = nullptr;


        while (cur || !st.empty())
        {

            while (cur)
            {
                st.push(cur);
                cur = cur->left;
            }


            TreeNode* temp = st.top();

            if (temp->right == nullptr || temp->right == prev)
            {
                v.push_back(temp->val);
                st.pop();
            }
            else
            {
                cur = temp->right;
            }

            prev = temp;
        }


        return v;
    }
};
